/**
 * ===========================================================================
 * 版权所有 湖南免了么网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.mianle.me
 * ===========================================================================
 * 11:27 2018/6/26
 */
package com.mianle.userapi.service.task04;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;

/**
 * @Author: yiyuan
 * @Description:
 * @Date: Created in 11:27 2018/6/26
 *
 */
@Component
@Slf4j
public class Task04 {

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    private ScheduledFuture<?> task;


    //采用注入的方式创建ThreadPoolTaskScheduler
    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }
    //任务开始
    public void startTask() {
        task = threadPoolTaskScheduler.schedule(new Runnable() {
            @Override
            public void run() {
                log.info(new Date()+"0/2 * * * * *");
            }
        }, new CronTrigger("0/2 * * * * *"));
        log.info("开始任务！");
    }
    //任务停止
    public String stopTask() {
        if (task != null) {
            task.cancel(true);
        }
        log.info("任务停止！");
        return "stopCron";
    }
    //更改计划，可以将更改的执行计划作为参数传入
    public void changePlan() {
        stopTask();
        task = threadPoolTaskScheduler.schedule(new Runnable() {
            @Override
            public void run() {
                log.info(new Date()+"*/5 * * * * *");
            }
        }, new CronTrigger("*/5 * * * * *"));
        log.info("改变任务！");
    }
}
